var request = require('request');
var Cache = require('jsoncache');
var cache = new Cache({ dir: './cache', life: 60*60*24*365, mode: 'json' });

var then = require('thenjs');
exports.getIPInfo = function (ip,cb) {
	then(function (defer) {
		cache.get(ip,function (err,doc) {
			if(err||!doc){
				defer(null,false);
			}else{
				cb(null,doc);
			}
		});
	}).then(function (defer,cacheDoc) {
		request('http://ip.taobao.com/service/getIpInfo.php?ip='+ip, function (error, response, body) {
			if (!error && response.statusCode == 200) {
				cache.set(ip,JSON.parse(body),defer);
				cb(error,JSON.parse(body));
				return;
			}
			cb(error,{});
		})
	})
}



